package org.zjt.rpc.netty.client;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.zjt.helloworld.domain.RequestMsgProto;
import org.zjt.rpc.domain.RpcMsgProto;
import org.zjt.rpc.service.RPCFacade;
import org.zjt.rpc.util.InvokeMethodExecuter;

/**
 * Created by zhangjuntao on 2017/3/16.
 */
public class RpcClientHandler extends ChannelHandlerAdapter {

    /**
     * Creates a client-side handler.
     */
    public RpcClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for (int i = 0; i < 10; i++) {
            ctx.write(createRequest());
        }
        ctx.flush();
    }

    //public abstract java.lang.String org.zjt.rpc.service.RPCFacade.sayHello(int,java.lang.String)
    public static RpcMsgProto.msg createRequest(){



        return InvokeMethodExecuter.createRpcMsgProto(RPCFacade.class.getDeclaredMethods()[0],new Object[]{24,"zhangsan"});
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Receive server response : [" + msg + "]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
